<style lang="less">
    .vertical-center-modal {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    #dialogue_box {
        height: 600px;
        background-color: black;
        display: flex;
        flex-direction: row;
        margin-right: auto;
        font-size: 15px;
        color: white;
        white-space: pre-wrap;
        overflow:scroll;
    }
	.printscreenimg{
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
<template>
    <div class="m-25 mt-65">
        <div class="normal-box-mod">
            <div class="normal-box-hd clearfix">
                <div class="normal-box-title">
                    <div class="decorate-square"></div>
                    <h2>安卓机器管理</h2>
                </div>
            </div>
            <div class="normal-box-bd">
                <div class="normal-list-page-mod">
                    <card class="mb-10">
                        <div class="normal-list-page-hd clearfix">
                            <Input v-model="queryData.name" placeholder="请输入名称" class="mr-10" style="width: 200px"/>
                            <Input v-model="queryData.imei" placeholder="请输入编号" class="mr-10" style="width: 200px"/>
                            <Button type="primary" custom-icon="iconfont icon-chaxun" size="small" @click="inQuire">查询
                            </Button>
                        </div>
                    </card>
                  <div class="mb-2">
                    <Button-group>
                      <Button custom-icon="iconfont icon-shanchusekuai" size="small" type="error" @click="batchDel">
                        删除
                      </Button>
                      <Button custom-icon="iconfont icon-fangkuai2" size="small" type="primary" @click="showCreateModal">
                        新建
                      </Button>
                      <Button custom-icon="iconfont icon-fangkuai2" size="small" type="primary" @click="showUpdModelBatch">
                        一键更新
                      </Button>
                    </Button-group>
                  </div>
                    <div class="normal-list-page-bd">
                        <Table border :loading="list.loading" :columns="list.columns" :data="list.tableData" @on-selection-change="selectionChange"></Table>
                    </div>
                    <div class="normal-list-page-ft clearfix">
                        <Page class="fr" :total="queryData.totalRecord" :page-size="queryData.pageSize"
                              :current="queryData.page" @on-change="changePage" @on-page-size-change="onPageSizeChange"
                              show-elevator show-total show-sizer></Page>
                    </div>
                </div>

              <Modal v-model="fleg" title="远程控制" :closable="true" :mask-closable="false"  width="1340px">
                <Button-group >
                  <i-button @click="showDowModel"><Icon type="code-download"></Icon>下载</i-button>
                  <i-button @click="showUpdModel">更新</i-button>
                  <i-button @click="sendCommand('screenShot')">截图</i-button>
                  <i-button @click="sendCommand('log')">查看日志</i-button>
                </Button-group>
                <div id="dialogue_box" ref="msg">
                  {{ contents }}
                </div>
                <br/>
                <Input v-model="message" placeholder="请输入命令" style="width: 600px" @on-enter="send" />&nbsp;
                <!--<Button type="success" @click="send">发送</Button>-->
                <div slot="footer"></div>
                <div slot="close"><Button type="error" @click="close" >关闭</Button></div>
              </Modal>
              <!--新建&修改-->
              <Modal v-model="modal.android.isShow" :loading="modal.android.loading" :mask-closable="false" :title="modal.android.title" @on-ok="postData">
                <Form ref="systemFrom" :model="modal.android.formData" :rules="modal.android.rules" :label-width="120">
                  <FormItem label="机器编号"  prop="imei">
                    <Input placeholder="请输入机器编号" v-model="modal.android.formData.imei" style="width:300px;"/>
                  </FormItem>
                  <FormItem label="机器名称"  prop="name">
                    <Input placeholder="请输入活动内容" v-model="modal.android.formData.name" style="width:300px;"/>
                  </FormItem>
                  <FormItem label="机器地址"  prop="address">
                    <Input placeholder="请输入机器地址" v-model="modal.android.formData.address" style="width:300px;"/>
                  </FormItem>
                  <FormItem label="备注"  prop="remark">
                    <Input placeholder="请输入备注" v-model="modal.android.formData.remark" style="width:300px;"/>
                  </FormItem>
                </Form>
              </Modal>
                <!--远程下载-->
                <Modal v-model="modal.download.isShow" :loading="modal.download.loading" :mask-closable="false"
                       :title="modal.download.title" @on-ok="downloadSubmit">
                    <Form ref="newDowData" :model="modal.download.formData" :rules="modal.download.rules">
                        <FormItem label="下载地址" prop="url">
                            <Input placeholder="请输入下载地址" v-model="modal.download.formData.url" style="width:300px;"/>
                        </FormItem>
                        <FormItem label="存放目录" prop="path">
                            <Input placeholder="请输入存放目录" v-model="modal.download.formData.path" style="width:300px;"/>
                        </FormItem>
                        <FormItem label="文件名" prop="filename">
                            <Input placeholder="请输入文件名" v-model="modal.download.formData.filename" style="width:300px;"/>
                        </FormItem>,
                    </Form>
                </Modal>
                <!--远程更新-->
                <Modal v-model="modal.update.isShow" :loading="modal.update.loading" :mask-closable="false"
                       :title="modal.update.title" @on-ok="updateSubmit">
                    <Form ref="newUpData" :model="modal.update.formData" :rules="modal.update.rules">
                        <FormItem label="更新地址" prop="url">
                            <Input placeholder="请输入更新地址" v-model="modal.update.formData.url" style="width:300px;"/>
                        </FormItem>
                        <FormItem label="打开的界面" prop="launchActivity">
                            <Input placeholder="请输入打开的界面" v-model="modal.update.formData.launchActivity" style="width:300px;"/>
                        </FormItem>
                        <FormItem label="包名" prop="packageName">
                            <Input placeholder="请输入包名" v-model="modal.update.formData.packageName" style="width:300px;"/>
                        </FormItem>
                        <FormItem label="版本号" prop="version">
                            <Input placeholder="请输入版本号" v-model="modal.update.formData.version" style="width:300px;"/>
                        </FormItem>
                    </Form>
                </Modal>
                <!--一键远程更新-->
                <Modal v-model="modal.updateBatch.isShow" :loading="modal.updateBatch.loading" :mask-closable="false"
                       :title="modal.updateBatch.title" @on-ok="updateBatchSubmit">
                  <Form ref="newUpDataBatch" :model="modal.updateBatch.formData" :rules="modal.updateBatch.rules">
                    <FormItem label="更新地址" prop="url">
                      <Input placeholder="请输入更新地址" v-model="modal.updateBatch.formData.url" style="width:300px;"/>
                    </FormItem>
                    <FormItem label="打开的界面" prop="launchActivity">
                      <Input placeholder="请输入打开的界面" v-model="modal.updateBatch.formData.launchActivity" style="width:300px;"/>
                    </FormItem>
                    <FormItem label="包名" prop="packageName">
                      <Input placeholder="请输入包名" v-model="modal.updateBatch.formData.packageName" style="width:300px;"/>
                    </FormItem>
                    <FormItem label="版本号" prop="version">
                      <Input placeholder="请输入版本号" v-model="modal.updateBatch.formData.version" style="width:300px;"/>
                    </FormItem>
                  </Form>
                </Modal>
                <!--显示截图-->
                <Modal v-model="modal.printscreen.isShow" :closable="true" title="截图" @on-visible-change="closeprintscreen" :width="modal.printscreen.width" >
                  <div class="printscreenimg">
                     <img :src="modal.printscreen.url"  id="printscreenimg"  alt="">
                  </div>
                   <div slot="footer"></div>
                </Modal>
            </div>
        </div>
    </div>
</template>
<script>
import androidApi from '@/api/ckMachineCenter/android.js'
import moment from 'moment'
import { Message } from 'iview'

export default {
  name: 'android',
  props: {
    msg: String
  },
  data () {
    return {
      id: '',
      androidId: '',
      contents: '',
      path: 'ws://192.168.0.107:6001',
      // path: 'ws://admin.ck9696.com:6001',
      socket: '',
      socketInit: '',
      message: '',
      fleg: false,
      starttime: 0,
      lasttime: '',
      time: 1002,
      // 弹出层数据
      modal: {
        android: {
          isShow: false,
          loading: true,
          type: 'create', // create 新建，update 修改
          title: '新建',
          rules: {
            name: [
              {
                required: true,
                message: '请填写机器名称',
                trigger: 'blur'
              }
            ]
          },
          formData: {}
        },
        printscreen: {
          width: 1050,
          isShow: false,
          url: ''
        },
        download: {
          isShow: false,
          loading: true,
          title: '下载',
          rules: {
            url: [
              {
                required: true,
                message: '请填写下载地址',
                trigger: 'blur'
              }
            ],
            path: [
              {
                required: true,
                message: '请填写存放目录',
                trigger: 'blur'
              }
            ],
            filename: [
              {
                required: true,
                message: '请填写文件名',
                trigger: 'blur'
              }
            ],
            cmdid: [
              {
                required: true,
                message: '请输入命令ID',
                trigger: 'blur'
              }
            ]
          },
          formData: {}
        },
        update: {
          isShow: false,
          loading: true,
          title: '更新',
          rules: {
            url: [
              {
                required: true,
                message: '请填写更新地址',
                trigger: 'blur'
              }
            ],
            packageName: [
              {
                required: true,
                message: '请填写包名',
                trigger: 'blur'
              }
            ],
            version: [
              {
                required: true,
                message: '请填写版本号',
                trigger: 'blur'
              }
            ],
            cmdid: [
              {
                required: true,
                message: '请输入命令ID',
                trigger: 'blur'
              }
            ]
          },
          formData: {}
        },
        updateBatch: {
          isShow: false,
          loading: true,
          title: '更新',
          rules: {
            url: [
              {
                required: true,
                message: '请填写更新地址',
                trigger: 'blur'
              }
            ],
            packageName: [
              {
                required: true,
                message: '请填写包名',
                trigger: 'blur'
              }
            ],
            version: [
              {
                required: true,
                message: '请填写版本号',
                trigger: 'blur'
              }
            ],
            cmdid: [
              {
                required: true,
                message: '请输入命令ID',
                trigger: 'blur'
              }
            ]
          },
          formData: {}
        }
      },
      // 列表
      list: {
        loading: false,
        selections: [],
        // 列表展示数据
        tableData: [],
        // 表格表头
        columns: [
          {
            type: 'selection',
            minWidth: 60,
            align: 'center'
          },
          /** 开始自动生成 */
          { title: '编号', align: 'center', key: 'imei', minWidth: 100 },
          { title: '名称', align: 'center', key: 'name', minWidth: 100 },
          { title: '地址', align: 'center', key: 'address', minWidth: 100 },
          { title: '坐标', align: 'center', key: 'poi', minWidth: 100 },
          { title: '版本号', align: 'center', key: 'versionCode', minWidth: 100 },
          { title: '备注', align: 'center', key: 'remark', minWidth: 100 },
          {
            title: '创建时间',
            align: 'center',
            key: 'createTime',
            minWidth: 100
          },
          {
            title: '更新时间',
            align: 'center',
            key: 'updateTime',
            minWidth: 100
          },
          /** 自动生成结束 */

          {
						  title: '操作',
						  align: 'center',
						  fixed: 'right',
						  minWidth: 130,
						  render: (h, params) => {
						    return h('div', [
						      h(
						        'Tooltip',
						        {
						          props: {
						            placement: 'left',
						            content: '远程连接'
						          },
						          style: {
						            cursor: 'pointer'
						          }
						        },
						        [
						          h(
						            'Button',
						            {
						              props: {
						                type: 'primary',
						                size: 'small'
						              },
						              style: {
						                marginRight: '5px',
						                padding: '1px 2px'
						              },
						              on: {
						                click: () => {
                            this.connection(params.row.imei, params.row.id)
						                }
						              }
						            },
						            [
						              h('Icon', {
						                props: {
						                  type: 'ios-wifi',
						                  size: 18
						                }
						              })
						            ]
						          )
						        ]
						      ),
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'left',
                      content: '编辑'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'primary',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            // this.showUpdateModal(params.index);
                            this.showUpdateModal(params.row.id)
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-bianjisekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                ),

                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'right',
                      content: '删除'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'error',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            this.delData([params.row.id])
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-shanchusekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                )
						    ])
						  }
          }
        ]
      },
      // 页面查询数据
      queryData: {
        limit: 10,
        page: 1,
        totalRecord: 0
      }
    }
  },
  methods: {
    // 获取列表
    getTableData () {
      const that = this
      that.queryData.totalRecord = undefined
      androidApi.getPageList(that.queryData)
        .then(res => {
          that.list.tableData = res.data.list
          that.queryData.totalRecord = res.data.totalRecord
          that.queryData.limit = res.data.pageSize
        })
        .catch(error => {
          Message.error(error)
        })
    },

    // 全选，不全选
    selectionChange (args) {
      this.list.selections = args
    },

    // 每页显示记录数变更
    onPageSizeChange (pageSize) {
      this.queryData.limit = pageSize
      this.getTableData()
    },

    // 换页
    changePage (page) {
      this.queryData.page = page
      this.getTableData()
    },
    selections () {
      let ids = []
      this.list.selections.forEach(element => {
				    that.androidId = element.imei
				    ids.push(element.id)
      })
      if (ids[0] == undefined) {
        this.$Message.error({
          content: '请先选择机器！',
          duration: 3
        })
      }
    },
    connection (imei, id) {
      const that = this
      that.androidId = imei
      if ('WebSocket' in window) {
        that.socket = new WebSocket(that.path)
      } else {
        alert('该浏览器不支持websocket!')
      }
      that.id = id
      console.log(123, that.socket)
      that.socket.onopen = function () {
        let a = `{"data":{"id":"${that.id}"},"msgId":"webLogin","sendTo":"${that.androidId}"}`
        console.log(123, a)
        that.socket.send(a)
        console.log('连接成功')
      }
      that.socket.onmessage = function (event) {
        let respObj = JSON.parse(event.data)
        if (respObj.msgId == 'screenshot') {
          // 截图
          that.modal.printscreen.url = respObj.data.img
          that.modal.printscreen.isShow = true
          var img = new Image()
          img.onload = function () {
            if (img.width > 1024) {
              document.getElementById('printscreenimg').width = 1024
              document.getElementById('printscreenimg').heigh = 1024 * (img.height / img.width)
            }
          }
          img.src = respObj.data.img
          return
        } else if (respObj.msgId == 'log') {

        } else if (respObj.msgId == 'install') {
          that.updateCommandLine(respObj.data.status)
          return
        } else if (respObj.msgId == 'download') {
          that.updateCommandLine(respObj.data.status)
          return
        } else if (respObj.msgId == 'login') {
          that.updateCommandLine('本次连接ID：' + respObj.data)
          return
        }
        that.updateCommandLine(respObj.data.result)
      }
      that.socket.onerror = function () {
        console.log('websocket通信发生错误！')
      }
      that.socket.onbeforeunload = function () {
        that.socket.close()
      }
      that.fleg = true
    },
    send () {
      let message = `{"data":{"cmd":"${this.message}"},"msgId":"cmd","sendTo":"${this.androidId}"}`
      this.socket.send(message)
      this.message = ''
    },
    sendCommand (cmd) {
      let message = `{"data":{},"msgId":"${cmd}","sendTo":"${this.androidId}"}`
      console.log(message)
      this.socket.send(message)
      this.message = ''
    },
    close () {
      let message = `{"data":{"cmd":"exit"},"msgId":"cmd","sendTo":"${this.androidId}"}`
      this.socket.send(message)
      this.socket.close()
      this.fleg = false
      this.contents = ''
      this.message = ''
      this.androidId = ''
    },
    // 刷新窗口数据
    updateCommandLine (line) {
      let message = `${this.contents}
                        ${line}`
      this.contents = message
      this.$nextTick(function () {
        var p = this.$refs.msg
        p.scrollTop = p.scrollHeight
      })
    },
    // 查询
    inQuire () {
			  const that = this
      that.queryData.page = 1
			  // gcDustbinApi.getPageList(that.queryData);
			  that.getTableData()
    },
    // 关闭截图弹框
    closeprintscreen (e) {
      const that = this
      that.modal.printscreen.isShow = e
    },
    // 显示下载弹窗
    showDowModel () {
      this.modal.download.title = '下载'
      this.modal.download.formData = {}
      this.modal.download.isShow = true
    },
    downloadSubmit () {
      let that = this
      this.$refs['newDowData'].validate(valid => {
        if (valid) {
          let url = this.modal.download.formData.url
          let path = this.modal.download.formData.path
          let filename = this.modal.download.formData.filename
          let message = `{"data":{"id":"${this.id}","url":"${url}","path":"${path}","filename":"${filename}"},"msgId":"download","sendTo":"${that.androidId}"}`
          this.socket.send(message)
          this.modal.download.isShow = false
          this.modal.download.loading = false
        } else {
          this.modal.download.loading = false
          this.$nextTick(() => {
            this.modal.download.loading = true
          })
        }
      })
    },
    showUpdModel () {
      this.modal.update.title = '更新'
      this.modal.update.formData = {}
      this.modal.update.isShow = true
    },
    showUpdModelBatch () {
      this.modal.updateBatch.title = '一键更新'
      this.modal.updateBatch.formData = {}
      this.modal.updateBatch.isShow = true
    },
    updateSubmit () {
      let that = this
      this.$refs['newUpData'].validate(valid => {
        if (valid) {
          let url = this.modal.update.formData.url
          let packageName = this.modal.update.formData.packageName
          let version = this.modal.update.formData.version
          let launchActivity = this.modal.update.formData.launchActivity

          let message = `{"data":{"id":"${this.id}","url":"${url}","launchActivity":"${launchActivity}","packageName":"${packageName}","version":"${version}"},"msgId":"install","sendTo":"${that.androidId}"}`
          this.socket.send(message)
          this.modal.update.isShow = false
          this.modal.update.loading = false
          that.$Notice.success({
            title: '更新成功!'
          })
        } else {
          this.modal.update.loading = false
          this.$nextTick(() => {
            this.modal.update.loading = true
          })
        }
      })
    },
    updateBatchSubmit () {
      let that = this
      this.$refs['newUpDataBatch'].validate(valid => {
        if (valid) {
          let url = this.modal.updateBatch.formData.url
          let packageName = this.modal.updateBatch.formData.packageName
          let version = this.modal.updateBatch.formData.version
          let launchActivity = this.modal.updateBatch.formData.launchActivity

          let message = `{"data":{"id":"${this.id}","url":"${url}","launchActivity":"${launchActivity}","packageName":"${packageName}","version":"${version}"},"msgId":"installBatch","sendTo":"${that.androidId}"}`
          this.socketInit.send(message)
          this.modal.updateBatch.isShow = false
          this.modal.updateBatch.loading = false
          that.$Notice.success({
            title: '更新成功!'
          })
        } else {
          this.modal.updateBatch.loading = false
          this.$nextTick(() => {
            this.modal.updateBatch.loading = true
          })
        }
      })
    },
    batchDel () {
      let ids = []
      this.list.selections.forEach(element => {
        ids.push(element.id)
      })
      if (!ids.length) {
        this.$Message.error({
          content: '请先选择要删除的项！',
          duration: 3
        })
      }
      this.delData(ids)
    },
    // 删除
    delData (ids) {
      if (!ids.length) {
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        content:
          '<p>您确认删除id为 <strong>' +
          ids.toString() +
          '</strong> 的记录吗?</p><p>删除后将无法撤销，请谨慎操作！</p>',
        loading: true,
        onOk: () => {
          androidApi.del({
            ids: ids
          }).then(res => {
            this.$Modal.remove()
            if (!res.code) {
              this.$Notice.success({
                title: '删除成功'
              })
              this.queryData.page = 1
              this.getTableData()
            } else {
              this.$Notice.error({
                title: res.message
              })
            }
          })
        }
      })
    },
    // 新建&修改
    postData () {
      const that = this
      that.$refs['systemFrom'].validate(valid => {
        if (valid) {
          if (!that.modal.android.formData.id) { // 新建
            androidApi.add(that.modal.android.formData)
              .then(res => {
                that.modal.android.loading = false
                if (!res.code) {
                  that.modal.android.isShow = false
                  that.getTableData()
                  that.$Notice.success({
                    title: '保存成功!'
                  })
                } else {
                  that.modal.android.isShow = true
                  that.$Notice.error({
                    title: res.message
                  })
                }
              })
              .catch(error => {
                Message.error(error)
              })
          } else { // 修改
            androidApi.update(that.modal.android.formData)
              .then(res => {
                that.modal.android.loading = false
                if (!res.code) {
                  that.modal.android.isShow = false
                  that.getTableData()
                  that.$Notice.success({
                    title: '保存成功!'
                  })
                } else {
                  that.modal.android.isShow = true
                  that.$Notice.error({
                    title: res.message
                  })
                }
              })
              .catch(error => {
                Message.error(error)
              })
          }
        } else {
          that.modal.android.loading = false
          that.$nextTick(() => {
            that.modal.android.loading = true
          })
        }
      })
    },
    // 显示新建弹窗
    showCreateModal () {
      this.modal.android.type = 'create'
      this.modal.android.title = '新建'
      this.modal.android.formData = {}
      this.modal.android.isShow = true
    },
    // 显示修改弹窗
    showUpdateModal (id) {
      this.modal.android.type = 'update'
      this.modal.android.title = '修改'
      // 不请求后端，直接list取对象
      // this.modal.mallAdvertising.formData = JSON.parse(
      //   JSON.stringify(this.list.tableData)
      // )[index];
      const that = this
      androidApi.getDetail(id).then(res => {
        that.modal.android.formData = res.data
      })
        .catch(error => {
          Message.error(error)
        })
      this.modal.android.isShow = true
    },
    // 查询
    inQuire () {
      const that = this
      that.getTableData()
    }
  },
  created () {
    this.getTableData()
    if ('WebSocket' in window) {
      this.socketInit = new WebSocket(this.path)
    } else {
      alert('该浏览器不支持websocket!')
    }
  }
}
</script>
